package com.xiguthings.waka.web.controller.maintainer;

import com.xiguthings.waka.dao.DataBaseStatus;
import com.xiguthings.waka.exception.BussinessException;
import com.xiguthings.waka.po.Maintainer;
import com.xiguthings.waka.po.MaintainerExample;
import com.xiguthings.waka.po.Paper;
import com.xiguthings.waka.po.PaperExample;
import com.xiguthings.waka.po.extpo.Page;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.service.maintainer.IMaintainerService;
import com.xiguthings.waka.shiro.CustomizedToken;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.base.ResponseEntity;
import com.xiguthings.waka.web.controller.paper.PaperVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/maintainer")
@Api(tags = {"运维用户"})
public class MaintainerController extends AbstractController {
    @Resource
    private IMaintainerService maintainerService;

    /**
     * 判断paperVo 如果是空的，报出异常
     *
     * @param maintainerVo
     */
    private void ifEmptyPaper(MaintainerVo maintainerVo, String msg) {
        if (maintainerVo == null || maintainerVo.getMaintainer() == null) {
            throwCodeEmptyException(msg);
        }
    }


    /**
     * 创建查询条件
     *
     * @param maintainerVo
     * @param example
     * @throws NumberFormatException
     */
    private void queryConditions(MaintainerVo maintainerVo, MaintainerExample example) throws NumberFormatException {

        MaintainerExample.Criteria criteria = example.createCriteria();
        // 如果查询条件为空的
        if (maintainerVo == null) {
            // 则查询所有未被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
            return;
        }

        // 如果有查询条件
        Maintainer maintainer = maintainerVo.getMaintainer();
        // 添加查询条件
        if (maintainer != null) {
            if (StringUtils.isNotBlank(maintainer.getMaintainerId())) {
                criteria.andMaintainerIdEqualTo(maintainer.getMaintainerId());
            }
            if (StringUtils.isNotBlank(maintainer.getAccount())) {
                criteria.andAccountLike("%" + maintainer.getAccount() + "%");
            }
            if (StringUtils.isNotBlank(maintainer.getName())) {
                criteria.andNameLike("%" + maintainer.getName() + "%");
            }
        }

        if (StringUtils.isNotBlank(maintainerVo.getInStatus())) {
            // 添加包含的状态
            String statuses = maintainerVo.getInStatus();
            String[] statusArr = statuses.split(",");
            List<Integer> statusList = new ArrayList<>();
            for (String str : statusArr) {
                statusList.add(new Integer(str));
            }
            criteria.andStatusIn(statusList);
        } else {
            // 如果状态的查询条件是空的，则查询没有被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
        }

    }


    /**
     * 修改或者添加
     *
     * @param maintainerVo
     * @return
     * @throws Exception
     */
    @ApiOperation(tags = {"1.控制台"}, value = "修改/添加", httpMethod = "POST", notes = "修改时，必须填写“maintainer.maintainerId”参数", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "maintainer.maintainerId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.account", value = "账号", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.password", value = "密码", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.name", value = "名称", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.status", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity save(@ApiIgnore MaintainerVo maintainerVo) throws Exception {
        ifEmptyPaper(maintainerVo, "无法操作空参数");
        Maintainer maintainer = maintainerVo.getMaintainer();

        String id = maintainer.getMaintainerId();
        String msg = null;
        if (StringUtils.isNotBlank(id)) {
            // 修改
            int row = maintainerService.updateByPrimaryKeySelective(maintainer);
            if (row > 0) {
                msg = "修改成功";
            } else {
                msg = "修改失败，可能数据看中不存在这条数据";
            }
        } else {
            // 添加
            int row = maintainerService.insert(maintainer);
            if (row > 0) {
                msg = "添加成功";
            } else {
                msg = "添加失败，请重试";
            }
        }
        return ajaxReturnMap(CODE_SUCCESS, msg, maintainer.getMaintainerId());
    }

    @ApiOperation(tags = {"1.控制台"}, value = "根据主键获取记录详情", httpMethod = "GET", notes = "maintainerId必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "maintainer.maintainerId", value = "主键id", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseEntity detail(@ApiIgnore MaintainerVo maintainerVo) throws Exception {
        ifEmptyPaper(maintainerVo, "无法操作空参数");
        Maintainer maintainer = maintainerVo.getMaintainer();

        String id = maintainer.getMaintainerId();
        if (StringUtils.isBlank(id)) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "主键不能为空");
        }

        return ajaxReturnMap(CODE_SUCCESS, null, maintainerService.selectByPrimaryKey(id));
    }

    @ApiOperation(tags = {"1.控制台"}, value = "删除", httpMethod = "GET", notes = "taskId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "maintainer.maintainerId", value = "主键id", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(@ApiIgnore MaintainerVo maintainerVo) throws Exception {
        ifEmptyPaper(maintainerVo, "无法操作空参数");
        Maintainer maintainer = maintainerVo.getMaintainer();

        String id = maintainer.getMaintainerId();
        if (StringUtils.isBlank(id)) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, "主键不能为空");
        }

        int row = maintainerService.deleteByPrimaryKey(id);
        String msg = null;
        if (row > 0) {
            msg = "删除成功";
        } else {
            msg = "在此之前，可能已经删除了这条数据";
        }

        return ajaxReturnMap(CODE_SUCCESS, msg, null);
    }

    /**
     * 分页查询
     *
     * @param maintainerVo
     * @param page
     * @return
     * @throws Exception
     */

    @ApiOperation(tags = {"1.控制台"}, value = "分页查询", httpMethod = "GET", notes = "可根据条件进行筛选", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "maintainer.maintainerId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.account", value = "账号", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.name", value = "名称", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码，如果没有值，则使用默认值。开始值从 1 开始计算", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "rows", value = "每页的数量,如果没有值，则使用默认值", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/pagelist")
    @ResponseBody
    public ResponseEntity pageList(@ApiIgnore MaintainerVo maintainerVo, @ApiIgnore Page page) throws Exception {
        MaintainerExample example = new MaintainerExample();
        queryConditions(maintainerVo, example);
        super.selectByPage(page, example, maintainerService);
        return ajaxReturnMap(CODE_SUCCESS, null, page);
    }

    @ApiOperation(tags = {"1.控制台"}, value = "运维用户登录", httpMethod = "GET", notes = "用户名密码必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "maintainer.account", value = "账号", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "maintainer.password", value = "密码", dataType = "string", required = true, paramType = "query")
    })
    @RequestMapping("/login")
    @ResponseBody
    public ResponseEntity login(@ApiIgnore MaintainerVo maintainerVo) throws Exception {
        // 判断参数是否为空
        ifEmptyPaper(maintainerVo, null);
        Maintainer maintainer = maintainerVo.getMaintainer();
        String account = maintainer.getAccount();
        String password = maintainer.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            throwCodeEmptyException(null);
        }

        CustomizedToken tk = new CustomizedToken(account, password, Key_loginType_maintainer, null);
        Subject subject = SecurityUtils.getSubject(); // 得到当前用户
        try {
            subject.login(tk); // 自动调用AuthRealm.doGetAuthenticationInfo
        } catch (AuthenticationException e) {
            throwHttpSendErrorExceptionException(CODE_NOT_LOGIN, "用户名或密码错误");
        }
        maintainer = (Maintainer) tk.getParam().get(SESSION_CRN_MAINTAINER);
        maintainer.setPassword(null);
        super.getSession().setAttribute(SESSION_CRN_MAINTAINER, maintainer);
        return ajaxReturnMap(CODE_SUCCESS, "登录成功", null);
    }

    @ApiOperation(tags = {"1.控制台"}, value = "运维用户登出", httpMethod = "GET", notes = "", response = ResponseEntity.class)
    @RequestMapping("/logout")
    @ResponseBody
    public ResponseEntity logout() throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if (session != null) {
            session.setAttribute(Key_httpSession_authority, null);
        }
        subject.logout();
        return ajaxReturnMap(CODE_SUCCESS, "安全退出成功", null);
    }



}
